﻿#ifndef COMBASE_H
#define COMBASE_H

#include <QObject>
#include <QSerialPort>
#include <QDataStream>
#include "ComCommon.h"

class ComBase : public QObject
{
    Q_OBJECT
public:
    explicit ComBase(QObject *parent = nullptr);
    virtual ~ComBase(){}

    static QMap<ComState, QString> mapComStateText;
    static QMap<ComClientType, QString> mapComClientTypeText;
    static void initComBaseStaticVar() {
        mapComStateText = {
                           {CS_Invalid, QObject::tr("<font color='red'>不可用</font>")},
                           {CS_Connected, QObject::tr("<font color='green'>连接成功</font>")},
                           {CS_UnConnected, QObject::tr("<font color='yellow'>断开连接</font>")}
        };

        mapComClientTypeText = {
            {CCT_Tcp, QObject::tr("Tcp")},
            {CCT_Serial, QObject::tr("Serial")},
            {CCT_Udp, QObject::tr("Udp")}
        };
    }

    void setConfig(const ComClientConfig& config);
    ComClientConfig getConfig() const {return mConfig;}
    void setReconnectEnable(bool isEnabel = false){mIsEnableReconnect = isEnabel;}


signals:
    void sigMsg(const QString &msg);
    void sigReceiveData(const QByteArray& data);
    void sigStateChanged(ComState state);

public slots:
    virtual void onInit() = 0;
    virtual void onQuit() = 0;
    void onWrite(const QString& data);
    void onWrite(const QByteArray& data);//发送数据
    void onConfigChanged(const ComClientConfig &p);

protected:
    void setState(const ComState& state);
    virtual void writeData(const QByteArray& data) = 0;
    virtual void disconnect() = 0;
    virtual void onReadyRead() = 0;
    virtual void processData(const QByteArray& data)=0;
public:
    ComClientConfig mConfig;
protected:
    ComState mState = CS_Invalid;
    bool mIsEnableReconnect = true;
};

#endif // COMBASE_H
